<template>
  <el-card class="box-card">
    <template #header>
      <el-button type="primary" :icon="Plus" @click="addTrademark"
        >添加</el-button
      >
    </template>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌Login">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.logoUrl"
          />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            :icon="Edit"
            color="#abcdef"
            @click="handelTrademark(row)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            color="#666666"
            @click="deleteTrademark(row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper,->, sizes,total"
      :total="total"
      @current-change="currentChange"
      @size-change="sizeChange"
    />
  </el-card>

  <el-dialog
    v-model="dialogFormVisible"
    :title="`${title}品牌`"
    @closed="clearTrademark"
  >
    <el-form :model="form" :rules="rules" status-icon ref="formRef">
      <el-form-item prop="tmName" label="品牌名称" label-width="100px">
        <el-input v-model="form.tmName" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="logoUrl" label="品牌Login" label-width="100px">
        <el-upload
          class="avatar-uploader"
          :action="`${BASE_URL}/admin/product/fileUpload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearTrademark">取消</el-button>
        <el-button type="primary" @click="addTrademarkData">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  reqTrademarkPageList,
  reqAddTrademarkData,
  reqChangTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import type {
  TrademarkRecords,
  Trademark,
} from "@/api/product/model/TrademarkModel";
import type { UploadProps, FormRules, FormInstance } from "element-plus";

//得到代理地址
const BASE_URL = import.meta.env.VITE_API_URL;
// 初始化当前页
const currentPage = ref<number>(1);
//初始化每页条数
const pageSize = ref<number>(3);
//总条数
const total = ref<number>();
//初始化全部的数据,格式是对象组成的数组
const tableData = ref<TrademarkRecords>([]);
//初始化弹框是否显示
const dialogFormVisible = ref(false);
//获取form组件实例,书写整体校验
const formRef = ref<FormInstance>();
//弹框初始化数据
const initData = () => ({
  id: undefined,
  tmName: "",
  logoUrl: "",
});
const form = reactive<Trademark>(initData());

//发送请求获取初始化数据
const getTrademarkPage = async () => {
  const re = await reqTrademarkPageList(currentPage.value, pageSize.value);
  // console.log(re);
  total.value = re.total;
  tableData.value = re.records;
};
//点击页面切换并发送请求
const currentChange = (current: number) => {
  // console.log(current);
  // 把点击的页码赋值给初始化页码
  currentPage.value = current;
  // 发送请求获取数据
  getTrademarkPage();
};
//点击改变每页条数
const sizeChange = (page: number) => {
  // 把点击的每页条数给初始化数据
  pageSize.value = page;
  //切换条数后回到第一页
  currentPage.value = 1;
  // 发送请求获取数据
  getTrademarkPage();
};
//点击添加弹出弹框
const addTrademark = () => {
  dialogFormVisible.value = true;
};
//文件上传成功之后的回调函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  form.logoUrl = response.data;
};
//上传之前的回调函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
//点击确认整理参数发送请求添加数据
const addTrademarkData = () => {
  //整体校验,需要获取form组件实例.因为要用到form身上的validate方法
  formRef.value?.validate(async (flag: boolean) => {
    if (flag) {
      // 修改是需要id 的,新增不需要,所以此处做个判断用来区分进入这个函数的请求有没有携带id,然后做出不同操作
      if (form.id) {
        await reqChangTrademark(form);
      } else {
        //  发送请求添加数据
        await reqAddTrademarkData(form);
        currentPage.value = 1;
      }

      //点击确认关闭弹窗
      dialogFormVisible.value = false;
      //添加成功弹窗
      ElMessage({
        message: `品牌${title.value}成功`,
        type: "success",
      });
      //添加成功后清空本次添加的内容
      Object.assign(form, initData());
      //为了清空当前一次的校验结果,以免留到下一次显示
      nextTick(() => {
        formRef.value?.clearValidate();
      });
      //发送请求获取最新数据
      getTrademarkPage();
    }
  });
};
//区别是添加成功还是修改成功
const title = computed(() => {
  return form.id ? "修改" : "添加";
});
//点击取消清空弹框内容
const clearTrademark = () => {
  //关闭弹窗
  dialogFormVisible.value = false;
  // 清空弹框数据
  Object.assign(form, initData());
  // Vue更新数据是同步,页面更新时异步
  // 此方法是为了再最近的一次页面更新之后立即执行此回调函数,清空校验结果
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};
//修改当前行的品牌信息
const handelTrademark = (row: Trademark) => {
  // 点击修改弹出弹框
  dialogFormVisible.value = true;

  Object.assign(form, row);
};
//点击删除弹出提示框
const deleteTrademark = (row: Trademark) => {
  ElMessageBox.confirm(`确实要删除${row.tmName}吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademark(row.id as number);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getTrademarkPage();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//自定义检验规则
const validatorName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("内容不能为空"));
  } else if (value.length < 2 || value.length > 6) {
    callback(new Error("品牌名称长度必须在2-6个字符之间"));
  } else {
    callback();
  }
};
// 校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    // { min: 2, max: 6, message: '品牌名称长度必须在2-6个字符之间', trigger: 'change' },
    { validator: validatorName, trigger: "change" },
  ],
  logoUrl: [{ required: true, message: "请输入品牌Login" }],
});

// 挂载后发送初始化请求数据
onMounted(() => {
  getTrademarkPage();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
